<?php
namespace app\modules\user\forms\login;

use app\common\forms\BaseForm;
use app\config\Constants;
use app\models\User;
use app\modules\user\services\UserService;
use yii\base\UserException;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class WechatLoginForm extends BaseForm
{
    public $code;
    public $encrypted_data;
    public $iv;

    /**
     * @var User
     */
    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            ['code','required','message'=>\Yii::t("app","code不能为空")],
            ['encrypted_data','required','message'=>\Yii::t("app","加密数据不能为空")],
            ['iv','required','message'=>\Yii::t("app","向量不能为空")]
        ];
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return \Yii::$app->getModule("user")->user->login($this->getUser());
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $wechat = \Yii::$app->wechat->getMiniProgram();
            $result = $wechat->auth->session($this->code);
            if(isset($result['errcode']) && $result['errcode'] != 0){
                throw new UserException($result['errmsg']);
            }
            $this->_user = UserService::findInfoByCredential($result['openid'],Constants::WECHAT);
            if($this->_user == null){
                //解密用户信息数据
                $user_info = $wechat->encryptor->decryptData($result['session_key'],$this->iv,$this->encrypted_data);
                //创建用户
                $this->_user = UserService::create($user_info,Constants::WECHAT);
            }
            //存储session_key
            \Yii::$app->getCache()->set($result['openid'],$result['session_key']);
        }

        return $this->_user;
    }
}